﻿using API;
using API.Product;
using Common;
using DevExpress.Xpo;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class CategoryBLL : BaseBLL
    {
        public void BatchInsert(DateTime? lastUpdateDate = null)
        {
            try
            {
                this.Request.LastUpdateDate = lastUpdateDate;
                ApiProduct dataProxy = ServiceProxy.ApiProductProxy();
                MP_Category[] categorys = dataProxy.GetCategorys(this.Request);
                if (categorys == null || categorys.Length <= 0) return;
                using (UnitOfWork uow = DatabaseSchema.UnitOfWork)
                {
                    foreach (MP_Category c in categorys)
                    {
                        P_Category category = new P_Category(uow);
                        category.CategoryID = c.CategoryID;
                        category.ParentID = string.Empty;
                        category.CategoryName = c.CategoryName;
                        category.StatusID = c.StatusID;
                        category.Sort = c.Sort;
                        category.Creator = c.Creator;
                        category.CreateDT = c.CreateDT;
                        category.Operator = c.Operator;
                        category.UpdateDT = c.UpdateDT.Value;
                        category.Remark = c.Remark;
                        category.Save();
                    }
                    uow.CommitChanges();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("CategoryBLL.BatchInsert", ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public DateTime MaxUpdateDate()
        {
            string sql = @"select Max(UpdateDT) from P_Category";
            object updateDate = DatabaseSchema.Session.ExecuteScalar(sql);
            if (updateDate != null)
                return Convert.ToDateTime(updateDate);
            return DateTime.Now.AddYears(-5);
        }
    }
}
